import { sysDictList } from '@/services/common';
import { getDeviceInfo, updateDeviceParams } from '@/services/deviceMsg';
import {
  patientLimitsList,
  patientLimitsUpdateBatch,
} from '@/services/patientMsg';
import { InputNumber, message, Modal, Select, Switch, Table, Tabs } from 'antd';
import React, { useImperativeHandle, useState } from 'react';
import './index.less';

const AlarmLimit = React.forwardRef((props: any, ref) => {
  const { refreshList } = props;
  const [modalOpen, setModalOpen] = useState(false);
  const [deviceParamsListData, setDeviceParamsListData] = useState<any>([]);
  const [patientLimitsListData, setPatientLimitsListData] = useState<any>([]);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [sysDictLevelListData, setSysDictLevelListData] = useState<any>([]);
  const [activeKey, setActiveKey] = useState<string>('1');
  const [modItem, setmodItem] = useState<any>(null);
  const optionGroups: any = {
    group1: [
      { label: '12.5mm/s', value: '12.5mm/s' },
      { label: '25mm/s', value: '25mm/s' },
      { label: '50mm/s', value: '50mm/s' },
    ],
    group2: [
      { label: '1/4', value: '1/4' },
      { label: '1/2', value: '1/2' },
      { label: '1', value: '1' },
      { label: '2', value: '2' },
    ],
    group3: [
      { label: 'I', value: '1' },
      { label: 'II', value: '2' },
      { label: 'III', value: '3' },
      { label: 'aVR', value: '4' },
      { label: 'aVL', value: '5' },
      { label: 'aVF', value: '6' },
      { label: 'V1', value: '7' },
      { label: 'V2', value: '8' },
      { label: 'V3', value: '9' },
      { label: 'V4', value: '10' },
      { label: 'V5', value: '11' },
      { label: 'V6', value: '12' },
    ],
    group4: [
      { label: 'I', value: '1' },
      { label: 'II', value: '2' },
      { label: 'III', value: '3' },
      { label: 'aVR', value: '4' },
      { label: 'aVL', value: '5' },
      { label: 'aVF', value: '6' },
      { label: 'V1', value: '7' },
      { label: 'V2', value: '8' },
      { label: 'V3', value: '9' },
      { label: 'V4', value: '10' },
      { label: 'V5', value: '11' },
      { label: 'V6', value: '12' },
    ],
  };

  const handleChangeLimit = (e: any, index: number, type: string) => {
    let targetVal = JSON.parse(JSON.stringify(patientLimitsListData));
    targetVal[index][type] = e;
    setPatientLimitsListData(targetVal);
  };
  const getBaseData = async (row: any) => {
    const patientLimitsRes = await patientLimitsList({
      patientId: row.patientId || '',
      pageNum: 1,
      pageSize: 10000,
    });
    if (patientLimitsRes?.code === 200) {
      setPatientLimitsListData(patientLimitsRes.rows);
    }
    const resLevel = await sysDictList({
      pageSize: 1000,
      pageNum: 1,
      itemClass: 'monitorLimitsLevel',
    });
    if (resLevel?.code === 200) {
      const data = resLevel.rows.map((its: any) => {
        return {
          label: its.itemName,
          value: its.itemValue,
        };
      });
      setSysDictLevelListData(data);
    }
    const deviceParamsRes = await getDeviceInfo({
      deviceId: row.deviceId || '',
    });
    if (deviceParamsRes?.code === 200) {
      setDeviceParamsListData(deviceParamsRes?.data?.deviceParamsList || []);
    }
  };
  const columns = [
    {
      title: '报警限名称',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: '最小值',
      dataIndex: 'lowerLimit',
      key: 'lowerLimit',
      render: (text: any, record: any, inx: any) => {
        return (
          <InputNumber
            placeholder="最小值"
            value={text}
            onChange={(e) => handleChangeLimit(e, inx, 'lowerLimit')}
          />
        );
      },
    },
    {
      title: '最大值',
      dataIndex: 'upperLimit',
      key: 'upperLimit',
      render: (text: any, record: any, inx: any) => {
        return (
          <InputNumber
            placeholder="最大值"
            value={text}
            onChange={(e) => handleChangeLimit(e, inx, 'upperLimit')}
          />
        );
      },
    },
    {
      title: '报警级别',
      dataIndex: 'level',
      key: 'level',
      render: (text: any, record: any, inx: any) => {
        return (
          <Select
            placeholder="报警级别"
            value={text}
            options={sysDictLevelListData}
            onChange={(e) => handleChangeLimit(e, inx, 'level')}
          />
        );
      },
    },
    {
      title: '报警开关',
      dataIndex: 'alarmSwitch',
      key: 'alarmSwitch',
      render: (text: any, record: any, inx: any) => {
        return (
          <Switch
            value={text == 1 ? true : false}
            onChange={(e) => handleChangeLimit(e, inx, 'alarmSwitch')}
          />
        );
      },
    },
  ];
  const handleChangeDeviceParams = (e: any, index: number, type: string) => {
    let targetVal = JSON.parse(JSON.stringify(deviceParamsListData));
    targetVal[index][type] = e;
    setDeviceParamsListData(targetVal);
  };
  const deviceParamsColumns = [
    {
      title: '设备参数名称',
      dataIndex: 'paramName',
      key: 'paramName',
    },
    {
      title: '设备参数编号',
      dataIndex: 'paramCode',
      key: 'paramCode',
    },
    {
      title: '设备参数键值',
      dataIndex: 'paramValue',
      key: 'paramValue',
      render: (text: any, record: any, inx: any) => {
        return (
          <Select
            placeholder="报警级别"
            style={{ width: 120 }}
            value={text}
            options={optionGroups[`group${record.paramCode}`]} // 动态绑定选项
            onChange={(e) => handleChangeDeviceParams(e, inx, 'paramValue')}
          />
        );
      },
    },
  ];

  const handleModalShow = async (row?: any) => {
    setmodItem(row || null);
    if (!modalOpen) {
      getBaseData(row);
    }
    setModalOpen(!modalOpen);
  };

  useImperativeHandle(ref, () => ({
    handleModalShow,
  }));
  return (
    <Modal
      open={modalOpen}
      className="screen-area-patient-msg"
      mask={false}
      width={1200}
      okText="保存"
      cancelText="关闭"
      confirmLoading={confirmLoading}
      onCancel={handleModalShow}
      onOk={async () => {
        setConfirmLoading(false);
        if (activeKey === '1') {
          const targetData = deviceParamsListData.map((its: any) => {
            return {
              paramId: its.paramId,
              paramValue: its.paramValue,
            };
          });
          const res = await updateDeviceParams({
            deviceId: modItem.deviceId,
            paramsList: targetData,
          });
          if (res?.code === 200) {
            setConfirmLoading(true);
            message.success('更新成功');
            handleModalShow();
            refreshList();
          }
        } else {
          const targetData = patientLimitsListData.map((its: any) => {
            return {
              ...its,
              alarmSwitch:
                its.alarmSwitch === '1' || its.alarmSwitch === true ? '1' : '0',
            };
          });
          const res = await patientLimitsUpdateBatch({
            patientLimitList: targetData,
          });
          if (res?.code === 200) {
            setConfirmLoading(true);
            message.success('更新成功');
            handleModalShow();
            refreshList();
          }
        }
        setConfirmLoading(true);
      }}
      destroyOnHidden={true}
    >
      <Tabs
        activeKey={activeKey}
        onChange={(key) => {
          setActiveKey(key);
        }}
        items={[
          {
            label: 'ECG管理',
            key: '1',
            children: (
              <Table
                dataSource={deviceParamsListData}
                columns={deviceParamsColumns}
                pagination={false}
                key={'id'}
              />
            ),
          },
          {
            label: '报警限管理',
            key: '2',
            children: (
              <Table
                dataSource={patientLimitsListData}
                columns={columns}
                pagination={false}
              />
            ),
          },
        ]}
      />
    </Modal>
  );
});

export default AlarmLimit;
